/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jtsan;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.commons.CodeSizeEvaluator;

/**
 * JVM support only methods with length less than 65536 bytes.
 * After instrumentation method can grow more than 3 times.
 * Too suppress Runtime Exceptions generated by long methods
 * we use check for length, throw CodeSizeLimiter.MethodTooLongException
 * if necessary and handle it in Agent.
 * 
 * @author Sergey Vorobyev
 */

public class CodeSizeLimiter extends CodeSizeEvaluator {

  private String methodName;
  private static final int METHOD_MAX_SIZE = 65536;

  public static class MethodTooLongException extends RuntimeException {

    private static final long serialVersionUID = 0L; // Avoid javac warning.
    private String methodName;

    public MethodTooLongException(String name) {
      methodName = name;
    }

    public String getMethodName() {
      return methodName;
    }
  }

  public CodeSizeLimiter(MethodVisitor mv, String name) {
    super(mv);
    methodName = name;
  }

  @Override
  public void visitEnd() {
    if (getMaxSize() > METHOD_MAX_SIZE) {
      throw new MethodTooLongException(methodName);
    }
  }
}